package server.phone.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;
import server.phone.dao.BillDAO;
import server.phone.dao.CashierDAO;

import com.opensymphony.xwork2.ActionSupport;
import com.utopia84.model.Bill;
import com.utopia84.model.Billandpdt;
import com.utopia84.model.Cashier;

public class SetCashierServlet extends ActionSupport {
	private static final long serialVersionUID = -7811568044252827351L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public SetCashierServlet(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
	}
	public void doGet()	throws  IOException {
		int flag = 0;
		boolean result=false;
		String cashierId = request.getParameter("cashierId");
		String createTime = request.getParameter("createTime");
		String closeTime = request.getParameter("closeTime");
		
		float different = Float.parseFloat(request.getParameter("different"));
		float actual = Float.parseFloat(request.getParameter("actual"));	
		
		List<Cashier> cash = new ArrayList<Cashier>();	
		Cashier c = new Cashier();
		c.setCashierId(cashierId);
		c.setCreateTime(createTime);
		c.setCloseTime(closeTime);
		
		c.setDifferent(different);
		c.setActual(actual);		
		cash.add(c);
		
		String controller=request.getParameter("controller");
		
		System.out.println("SetCashier:controller="+controller+";cashierId="+cashierId+";createTime="+createTime+
				";closeTime="+closeTime+";different="+different+";actual="+actual);
		
		float initMoney;
		if(controller.equals("add")){
			try {
				initMoney = Float.parseFloat(request.getParameter("initMoney"));
				c.setInitMoney(initMoney);
				CashierDAO cd = new CashierDAO();
				flag = cd.saveCashier(cash);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		else{
			try {
				CashierDAO cd = new CashierDAO();
				result = cd.updateCashier(cashierId,closeTime,different,actual);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		JSONObject jObject = new JSONObject();
		try {
			if (flag==1||result==true)
				jObject.put("ret", "success");
			else
				jObject.put("ret", "error");
		} catch (Exception e) {
			jObject.put("ret", "error");
		}

		PrintWriter out = response.getWriter();
		out.println(jObject);
		out.flush();
		out.close();

	}

}
